import { Button, Card, Form, Input, message, Space, Table, Modal } from 'antd'
import {DeleteOutlined, EditOutlined, ExclamationCircleFilled, SearchOutlined} from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table'
import { delHospitalSetById, delHospitalSetList, getHospitalSetList } from '@/api/hospital/hospitalSet'
import { IHospitalSetList } from '@/api/hospital/model/hospitalSetType'
import { useNavigate } from 'react-router-dom'

const { confirm } = Modal;

export default function HospitalSet() {
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            width: 80,
            align:'center',
            render(value:any,row:any,index:number) {
                return (current-1) *pageSize +(index + 1)
            }
        },
        {
            title: '医院名称',
            dataIndex:'hosname'
        },
        {
            title: '医院编号',
            dataIndex:'hoscode'
        },
        {
            title: 'api基础路径',
            dataIndex: 'apiUrl'
        },
        {
            title: '签名',
            dataIndex: 'signKey'
        },
        {
            title: '联系人手机号',
            dataIndex: 'contactsName'
        },
        {
            title: '联系人姓名',
            dataIndex: 'contactsPhone'
        },
        {
            title: '操作',
            width: 120,
            fixed: 'right',
            render(row:any) {
                return (
                    <Space>
                        <Button onClick={() => navigate('/syt/hospital/hospitalSet/edit/' + row.id)} className='bor-r' type='primary' icon={<EditOutlined/>}></Button>
                        <Button onClick={() => deleteById(row.id)} className='bor-r'  type="primary" danger  icon={<DeleteOutlined/>}></Button>
                    </Space>

                )
            }
        }
    ]
    // 编程式导航
    const navigate = useNavigate()
    // 声明状态
    const [form] = Form.useForm() // 用来获取表单中输入的数据
    let [current, setCurrent] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(5)
    let [total, setTotal] = useState<number>(10)
    // 医院设置列表类型
    let [hospitalSetList, setHospitalSetList] = useState<IHospitalSetList>([])
    let [hosname, setHosname] = useState<string>('')
    let [hoscode, setHoscode] = useState<string>('')
    let [selectedKeys, setSelectedKeys] = useState<React.Key[]>([])
    // 加载loading效果
    let [loading, setLoading] = useState(false)

     // 获取接口列表数据,完成首屏数据渲染(公共函数)
     async function hospSetList() {
        setLoading(true)
        let {records, total}= await getHospitalSetList(current,pageSize,hosname,hoscode)
        // console.log(records,total);
        // 设置状态
        setHospitalSetList(records)
        setTotal(total)
        setLoading(false)
    }

    // 根据搜索框获取数据，并重发请求(这里通过改变hosname/hoscode的值，并在useEffect中监听，值发生变化就重发请求)
    const searchSetList = () => {
        // 获取用户输入的hosname，hoscode
        let {hosname, hoscode} = form.getFieldsValue()
        // console.log(form.getFieldsValue());
        
        setHosname(hosname || '')
        setHoscode(hoscode || '')
        current !== 1 && setCurrent(1)
    }
    // 清除搜索框中的数据，并重发请求(原理同上，都是监听数据变化，数值变化重发请求)
    const clear = () => {
        // 重置表单hosname hoscode ==》界面
        // 重置表单状态 hosname 和 hoscode ==》 重发请求
        form.resetFields()
        setHosname('')
        setHoscode('')
        setCurrent(1)
    }
    // 删除列表数据
    const deleteById = (id:string) => {
        // 删除确认框
        confirm({
            title: '温馨提示?',
            icon: <ExclamationCircleFilled />,
            content: '你确定要删除吗?',
            async onOk() {
                try{
                    await delHospitalSetById(id)
                    message.success('删除成功')
                    hospSetList()
                }catch(err) {
                    message.error('删除失败')
                }
            },
            onCancel() {
              message.warning('删除取消');
            },
          });
       
        
    }
    // 批量删除列表数据
    const deleteList = () => {
        // 删除确认框
        confirm({
            title: '温馨提示?',
            icon: <ExclamationCircleFilled />,
            content: '你确定要删除所选数据吗?',
            async onOk() {
                try{
                    await delHospitalSetList(selectedKeys)
                    setSelectedKeys([])
                    message.success('批量删除成功')
                    hospSetList()
                }catch(err) {
                    message.error('批量删除失败')
                }
            },
            onCancel() {
              message.warning('批量删除取消');
            },
        });
    }
   
    useEffect(() => {
        hospSetList() // 获取列表数据

    }, [current,pageSize,hoscode,hosname])
  return (
    <div>
        <Card>
            {/* 第一行 搜索查询按钮 */}
            <Form
            layout='inline'
            form= {form}
            name= 'hospSetList'
            onFinish={searchSetList}>
                <Form.Item name='hosname'>
                    <Input className='bor-r' placeholder='医院名称'></Input>
                </Form.Item>
                <Form.Item name='hoscode'>
                    <Input className='bor-r' placeholder='医院编号'></Input>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button className='bor-r' type='primary'icon={<SearchOutlined/>} htmlType="submit"></Button>
                        <Button className='bor-r' onClick={clear} disabled={!hosname && !hoscode}>清空</Button>
                    </Space>
                   
                </Form.Item>
    
            </Form>
            {/* 添加，删除按钮 */}
            <Form>
                <Space className='mar-t'>
                    <Button onClick={()=> navigate('/syt/hospital/hospitalSet/add')} className='bor-r' type='primary'>添加</Button>
                    <Button onClick={() => deleteList()} className='bor-r' disabled={selectedKeys.length === 0}>批量删除</Button>
                </Space>
            </Form>
            {/* table表格 */}
            <Table
                loading={loading}
                className='mar-t'
                columns={columns}
                rowKey={'id'}
                dataSource={hospitalSetList}
                scroll= {{x: 1500}} 
                rowSelection={{
                    onChange(selectedKeys:React.Key[],rows: any){
                        // console.log(selectedKeys);
                        setSelectedKeys(selectedKeys)
                        
                    } 
                }}
                pagination={{
                    current,
                    pageSize,
                    total,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [3,5,10,20],
                    onChange:(page:number,pageSize: number) => {
                        setCurrent(page)
                        setPageSize(pageSize)
                    }
                }}
            />
        </Card>
    </div>
  )
}
